from selenium import webdriver
from HTMLTestRunner import HTMLTestRunner
import unittest
import time
import os

host = 'http://172.16.70.38/ecshop/'
backhost = 'http://172.16.70.38/ecshop/admin'


def browser_operation(browser='chrome'):
    """
    判断使用的浏览器；
    打开浏览器;
    browser：浏览器
    窗口最大化
    """
    # 添加chrome浏览器无头模式
    options = webdriver.ChromeOptions()
    # options.add_argument('-headless')

    if browser == 'chrome':
        return webdriver.Chrome(options=options)
    elif browser == 'firefox':
        return webdriver.Firefox()
    elif browser == 'ie':
        return webdriver.Ie()
    elif browser == 'edge':
        return webdriver.Edge()
    else:
        print('请使用以下浏览器:chrome|firefox|ie|edge')


def get_test_report(fname, case):
    """
    执行测试用例，生成测试报告
    :param fname: 报告文件名称，str
    :param case: 测试用例名称，str
    :return: 测试报告
    """
    # 获取路径目录
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # 准备测试用例路径
    case_path = path + '/case'
    # 准备写入文件路径
    report_path = path + '/report'
    report = os.path.abspath(report_path)
    # 准备文件，文件名规则：年-月-日-时-分-秒-fname.html
    filename = time.strftime('%Y-%m-%d-%H-%M-%S') + f'-{fname}.html'
    filepath = os.path.join(report, filename)

    # loader
    loader = unittest.defaultTestLoader.discover(case_path, f'*{case}*')

    # runner
    # 写入文件，执行测试用例，生成测试报告
    with open(filepath, 'wb') as f:
        runner = HTMLTestRunner(
            title='ecshop测试报告张剑组',
            stream=f,
            tester='张剑, 梅咏, 李芸, 江慧, 程琦, 王怡',
            description='ecshop测试报告张剑组',
            verbosity=2
        )
        runner.run(loader)


if __name__ == '__main__':
    get_test_report('ecshop测试报告', 'case')
